User Input

Often, a program needs to be executed for different values depending upon the user of the program. In this case, your program will need to ask (prompt) the user for input values. The most direct way to get user input is to use the input() function to get values entered via the keyboard. This function accepts a single argument that is a string of characters to display to the user. This string is called the user prompt and is used to tell the user what type of information the program is expecting. What ever the user types on the keyboard, in response to the prompt, is then be stored in a variable for use in your program.

The Matlab command that is used for this is the input() function. The input function prints out a message asking for input and returns the value(s) that the user types on the keyboard. Type the following into a new editor window and save the files as sort_list.m. Then, run your script by clicking the Run button.

    list1 = input(' Type in a vector of integers: ' ) 
    list2 = sort( list1 ) 

Here is the result of executing this script:

>> sort_list
Type in a vector of integers: [ 8 2 4 7 12 2 3 77 1 ]

list1 = 

     8   2   4   7   12   2   3   77   1 
     
list2 =
 
     1   2   2   3   4   7   8   12   77 

The first line of the program uses the input() function to display the prompt, "Type in a vector of integers: " and then saves the vector that the user entered as list1.

The second line of the script sorts the vector, saves it as list2, and displays the results.

In the next module, you will learn about another way to get data from the user, file input.